
/******* SERVEUR TCP **************/

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>

#define PORTS "2058"
#define TAILLE_BUF 256

int main(int argc, char *argv[]) {
    int sockfd, new_fd, rv, sin_size, f, cpt_rd;
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr their_addr;
    char buf[TAILLE_BUF];

    memset(&hints, 0, sizeof (hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    // use my IP
    rv = getaddrinfo(NULL, PORTS, &hints, &servinfo);

    if (rv != 0) {
        printf("getaddrinfo: %s\n", gai_strerror(rv));
        return (1);
    }

    // Création socket et attachement
    for (p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL) {
        perror("server: failed to bind\n");
        exit(2);
    }

    freeaddrinfo(servinfo); // Libère structure
    listen(sockfd, 5);

    f = open("./testServer.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH);

    if (f == -1) {
        perror("serveur: Erreur creation fichier\n");
        exit(1);
    }

    printf("Serveur en attente de connexion\n");

    while (1) {
        sin_size = sizeof (their_addr);
        new_fd = accept(sockfd, &their_addr, &sin_size);

        printf("Connexion client acceptee\n");
        cpt_rd = recv(new_fd, buf, TAILLE_BUF, 0);
        while (cpt_rd == TAILLE_BUF) {
            write(f, buf, cpt_rd);
            printf("%d octects ecrits dans le fichier serveur :\n", cpt_rd);
            printf("%s\n", buf);
        }

        if (cpt_rd == -1) {
            perror("serveur: Erreur lecture socket\n");
        }

        if (cpt_rd < TAILLE_BUF || cpt_rd == 0) {
            write(f, buf, cpt_rd);
            close(f);
        }

        close(new_fd);
    }

    close(sockfd);

    exit(0);
}

